package com.hfy.user.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.hfy.model.dto.UserDto;
import com.hfy.model.po.user.UserPo;
import com.hfy.user.mapper.LoginMapper;
import com.hfy.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import result.Result;
import utils.CheckUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static constants.RedisConstants.LOGIN_TOKEN_KEY;
import static constants.RedisConstants.LOGIN_TOKEN_TTL;

/**
 * @ author 韩
 *   time: 2024/5/10 8:33
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private LoginMapper loginMapper;
    
    @Override
    public Result login(UserDto dto, HttpServletRequest request) {

        String originalAccount = dto.getAccount();
        if (!CheckUtils.theStringIsLong(originalAccount)) {
            return Result.error("你知道的账号是一串数字");
        }

        Long account = Long.parseLong(originalAccount);
        String password = dto.getPassword();

        // 1.先校验参数
        if (StringUtils.isBlank(account.toString()) || StringUtils.isBlank(password)) {
            return Result.error("账号或密码为空");
        }
        UserPo user = loginMapper.selectByAccount(account);
        if (user == null) {
            return Result.error("不存在该账号");
        }

        // 2.比对密码
        if (!password.equals(user.getPassword())) {
            return Result.error("密码错误");
        }
        // 3.代表密码正确了 就进行成功后的操作 生成一个uuid放到redis里，用hash类型,key为token value为数据
        String token = UUID.randomUUID().toString();


        String tokenKey = LOGIN_TOKEN_KEY + token;

        redisTemplate.opsForHash().put(tokenKey,"account",String.valueOf(user.getAccount()));
        redisTemplate.opsForHash().put(tokenKey,"username",user.getUsername());
        redisTemplate.opsForHash().put(tokenKey,"avatar",user.getAvatar() == null ? "" : user.getAvatar());
        redisTemplate.opsForHash().put(tokenKey,"loginTime", LocalDateTime.now().toString());
        redisTemplate.expire(tokenKey,LOGIN_TOKEN_TTL, TimeUnit.DAYS);

        request.getSession().setAttribute("account", account);
        return Result.ok(token,"登录成功");
    }
}
